package com.hugehard.here;

import java.util.ArrayList;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.hb.views.PinnedSectionListView;
import com.hb.views.PinnedSectionListView.PinnedSectionListAdapter;
import com.hugehard.here.ContactsManager.ContactItem;
import com.pinyin4android.PinyinUtil;

public class AllContactView {
	private final static String TAG = AllContactView.class.getSimpleName();
	private View mView = null;
	private Context mContext = null;
	private FastScrollAdapter mAdapter = null;
	private LayoutInflater mInflater = null;
	
	public AllContactView(Context context) {
		mContext = context;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		PinnedSectionListView listView = new PinnedSectionListView(context);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			listView.setFastScrollAlwaysVisible(true);
		}
		listView.setShadowVisible(false);
		mView = listView;
		
		ArrayList<ContactItem> normalItems = ContactsManager.getInstance().getNormalContactItemList();
		ArrayList<ContactItem> abnormalItems = ContactsManager.getInstance().getAbnormalContactItemList();

		mAdapter = new FastScrollAdapter(context,
				R.layout.contact_item, R.id.contact_name_textview);
		int sectionsNumber = abnormalItems.isEmpty() ? 0 : 1;

		String temp = "";
		for (int i = 0; i < normalItems.size(); i++) {
			ContactItem contactItem = normalItems.get(i);
			Item item = new Item(Item.ITEM, contactItem.mContactName, contactItem.mPhoneNumber);
			item.pinyin = contactItem.mPinyin;
			if (item != null) {
				String sectionStr = item.pinyin.substring(0, 1);
				if (temp.equals(sectionStr) == false) {
					sectionsNumber++;
					temp = sectionStr;
				}
			}
		}

		mAdapter.prepareSections(sectionsNumber);

		int sectionPosition = 0, listPosition = 0;
		if (abnormalItems.isEmpty() == false) {
			Item section = new Item(Item.SECTION, "#", null);
			section.sectionPosition = sectionPosition;
			section.listPosition = listPosition++;
			mAdapter.onSectionAdded(section, sectionPosition);
			mAdapter.add(section);
			for (int i = 0; i < abnormalItems.size(); i++) {
				ContactItem contactItem = abnormalItems.get(i);
				Item item = new Item(Item.ITEM, contactItem.mContactName, contactItem.mPhoneNumber);
				item.sectionPosition = sectionPosition;
				item.listPosition = listPosition++;
				item.phoneType = contactItem.mType;
				mAdapter.add(item);
			}
			sectionPosition++;
		}

		temp = "";
		sectionPosition--;
		for (int i = 0; i < normalItems.size(); i++) {
			ContactItem contactItem = normalItems.get(i);
			Item item = new Item(Item.ITEM, contactItem.mContactName, contactItem.mPhoneNumber);
			item.pinyin = contactItem.mPinyin;
			String sectionStr = item.pinyin.substring(0, 1);
			sectionStr = sectionStr.toUpperCase(Locale.getDefault());
			if (temp.equals(sectionStr) == false) {
				sectionPosition++;
				Item section = new Item(Item.SECTION, sectionStr, null);
				section.sectionPosition = sectionPosition;
				section.listPosition = listPosition++;
				mAdapter.onSectionAdded(section, sectionPosition);
				mAdapter.add(section);
				temp = sectionStr;
			}

			item.sectionPosition = sectionPosition;
			item.listPosition = listPosition++;
			item.phoneType = contactItem.mType;
			mAdapter.add(item);
		}
		listView.setAdapter(mAdapter);
		mAdapter.notifyDataSetChanged();
		listView.setOnItemClickListener(mOnItemClickListener);
	}
	
	private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			LayoutInflater inflater = (LayoutInflater)
			        mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View dialogView = inflater.inflate(R.layout.hh_dialog,
			        null);

			TextView text = (TextView) dialogView.findViewById(R.id.hh_dialog_textview);
			String contentStr = mContext.getResources().getString(R.string.hh_dialog_content);
			final Item item = mAdapter.getItem(arg2);
			
			if (item != null && item.type == Item.ITEM) {
				text.setText(contentStr + " " + item.text);
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				builder.setView(dialogView);
				final AlertDialog alertDialog = builder.create();
				
				View cancelBtn = dialogView.findViewById(R.id.btn_cancel);
				cancelBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						alertDialog.cancel();
					}
				});
				
				View okBtn = dialogView.findViewById(R.id.btn_ok);
				okBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {						
						LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
						Criteria crit = new Criteria();
						crit.setAccuracy(Criteria.ACCURACY_FINE);
						String provider = locationManager.getBestProvider(crit, true);
						Location location = locationManager.getLastKnownLocation(provider);
						double latitude = location.getLatitude();
						double longtiude = location.getLongitude();
						String smsText = String.format(Locale.getDefault(), "I'm here! (%f, %f)", latitude, longtiude);
						
						try {
							SmsManager smsManager = SmsManager.getDefault();
							smsManager.sendTextMessage(item.phone, null,
									smsText, null, null);
							Toast.makeText(mContext, "SMS Sent!",
									Toast.LENGTH_LONG).show();
						} catch (Exception e) {
							Toast.makeText(mContext,
									"SMS faild, please try again later!",
									Toast.LENGTH_LONG).show();
							e.printStackTrace();
						}
						alertDialog.cancel();
					}
				});
				
				alertDialog.show();
			}
		}
	};

	public View getView() {
		return mView;
	}

	private class Item implements Comparable<Item> {

		public static final int ITEM = 0;
		public static final int SECTION = 1;

		public final int type;
		public final String text;
		public final String phone;
		public int phoneType;
		public String pinyin;

		public int sectionPosition;
		public int listPosition;

		public Item(int type, String name, String phone) {
			this.type = type;
			this.text = name;
			this.phone = phone;
		}

		@Override
		public String toString() {
			return text;
		}

		@Override
		public int compareTo(Item another) {
			String contactName = PinyinUtil.toPinyin(mContext, text);
			String anotherContactName = PinyinUtil.toPinyin(mContext, another.text);
			return contactName.compareTo(anotherContactName);
		}
	}

	private class SimpleAdapter extends ArrayAdapter<Item> implements
			PinnedSectionListAdapter {

		private final int[] COLORS = new int[] {
			R.color.light_cornflower_blue_1,
			R.color.light_cyan_1,
			R.color.light_green_1,
			R.color.light_magenta_1,
			R.color.light_orange_1,
			R.color.light_purple_1,
			R.color.light_red_1,
			R.color.light_blue_1,
			R.color.light_yellow_1
		};

		public SimpleAdapter(Context context, int resource,
				int textViewResourceId) {
			super(context, resource, textViewResourceId);
		}
		
		class ViewHolder {
			public TextView mContactNameTv = null;
			public ImageView mPhoneTypeIv = null;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.contact_item, parent, false);
				viewHolder = new ViewHolder();
				viewHolder.mContactNameTv = (TextView) convertView.findViewById(R.id.contact_name_textview);
				viewHolder.mPhoneTypeIv = (ImageView) convertView.findViewById(R.id.contact_phone_type_imageview);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			Item item = getItem(position);
			if (item != null) {
				viewHolder.mContactNameTv.setTextColor(Color.DKGRAY);
				viewHolder.mContactNameTv.setText(item.text);
				if (item.type == Item.SECTION) {
					convertView.setBackgroundColor(parent.getResources().getColor(
							COLORS[item.sectionPosition % COLORS.length]));
				}
				if (item.phoneType == ContactsContract.CommonDataKinds.Phone.TYPE_HOME) {
					viewHolder.mPhoneTypeIv.setImageResource(R.drawable.phone_type_home);
					viewHolder.mPhoneTypeIv.setVisibility(View.VISIBLE);
				} else if (item.phoneType == ContactsContract.CommonDataKinds.Phone.TYPE_WORK) {
					viewHolder.mPhoneTypeIv.setImageResource(R.drawable.phone_type_work);
					viewHolder.mPhoneTypeIv.setVisibility(View.VISIBLE);
				} else {
					viewHolder.mPhoneTypeIv.setVisibility(View.GONE);
				}
			}
			return convertView;			
		}

		@Override
		public int getViewTypeCount() {
			return 2;
		}

		@Override
		public int getItemViewType(int position) {
			return getItem(position).type;
		}

		@Override
		public boolean isItemViewTypePinned(int viewType) {
			return viewType == Item.SECTION;
		}

	}

	private class FastScrollAdapter extends SimpleAdapter implements
			SectionIndexer {

		private Item[] sections;

		public FastScrollAdapter(Context context, int resource,
				int textViewResourceId) {
			super(context, resource, textViewResourceId);
		}

		protected void prepareSections(int sectionsNumber) {
			sections = new Item[sectionsNumber];
		}

		protected void onSectionAdded(Item section, int sectionPosition) {
			sections[sectionPosition] = section;
		}

		@Override
		public Item[] getSections() {
			return sections;
		}

		@Override
		public int getPositionForSection(int section) {
			if (section >= sections.length) {
				section = sections.length - 1;
			}
			return sections[section].listPosition;
		}

		@Override
		public int getSectionForPosition(int position) {
			if (position >= getCount()) {
				position = getCount() - 1;
			}
			return getItem(position).sectionPosition;
		}

	}
}
